<template>
  <el-dialog
      v-model="visible"
      title="预设管理"
      width="1200px"
      @close="handleClose"
      class="preset-manager-dialog"
  >
    <div class="preset-manager">
      <!-- 搜索和操作栏 -->
      <div class="manager-header">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索预设名称或描述"
            prefix-icon="Search"
            clearable
            style="flex: 1; max-width: 300px;"
            @input="handleSearch"
        />

        <div class="header-actions">
          <!-- 批量操作 -->
          <div class="batch-actions" v-if="selectedPresets.length > 0">
            <el-tag type="info" size="small">
              已选择 {{ selectedPresets.length }} 项
            </el-tag>
            <el-button size="small" @click="clearSelection">
              <el-icon><Close /></el-icon>
              清空选择
            </el-button>
            <el-button size="small" type="danger" @click="batchDeletePresets">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button size="small" type="success" @click="exportSelectedPresets">
              <el-icon><Download /></el-icon>
              导出选中
            </el-button>
          </div>

          <!-- 常规操作 -->
          <div class="normal-actions" v-else>
            <el-button size="small" @click="showImportDialog = true">
              <el-icon><Upload /></el-icon>
              导入预设
            </el-button>
            <el-button size="small" @click="exportAllPresets">
              <el-icon><Download /></el-icon>
              导出全部
            </el-button>
            <el-button type="primary" size="small" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              新建预设
            </el-button>
            <el-button size="small" @click="loadPresets">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 视图切换 -->
      <div class="view-controls">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button value="grid">
            <el-icon><Grid /></el-icon>
            网格视图
          </el-radio-button>
          <el-radio-button value="list">
            <el-icon><List /></el-icon>
            列表视图
          </el-radio-button>
        </el-radio-group>

        <div class="selection-controls">
          <el-checkbox
              v-model="selectAll"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
          >
            全选
          </el-checkbox>
        </div>
      </div>

      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="presets-grid" v-loading="loading">
        <div
            v-for="preset in currentPagePresets"
            :key="preset.id"
            class="preset-card"
            :class="{
              selected: selectedPreset?.id === preset.id,
              checked: isPresetSelected(preset.id)
            }"
            @click="selectPreset(preset)"
        >
          <!-- 选择框 -->
          <el-checkbox
              :model-value="isPresetSelected(preset.id)"
              @click.stop
              @change="togglePresetSelection(preset)"
              class="preset-checkbox"
          />

          <div class="preset-header">
            <h4 class="preset-name">{{ preset.name }}</h4>
            <div class="preset-actions">
              <el-button
                  size="small"
                  text
                  @click.stop="editPreset(preset)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                  size="small"
                  text
                  @click.stop="duplicatePreset(preset)"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
              <el-button
                  size="small"
                  text
                  type="danger"
                  @click.stop="deletePreset(preset)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>

          <div class="preset-description">
            {{ preset.description || '无描述' }}
          </div>

          <div class="preset-params">
            <el-tag size="small">{{ preset.canvas_width }}×{{ preset.canvas_height }}</el-tag>
            <el-tag size="small" type="success">{{ preset.output_format?.toUpperCase() }}</el-tag>
            <el-tag size="small" type="info">人物×{{ preset.video_scale }}</el-tag>
            <el-tag size="small" type="warning">背景×{{ preset.bg_scale }}</el-tag>
          </div>

          <div class="preset-meta">
            <small>创建时间: {{ formatDate(preset.created_time) }}</small>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="presets-table" v-loading="loading">
        <el-table
            :data="currentPagePresets"
            @selection-change="handleTableSelection"
            @row-click="selectPreset"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="预设名称" min-width="150" />
          <el-table-column label="画布尺寸" width="120">
            <template #default="{ row }">
              {{ row.canvas_width }}×{{ row.canvas_height }}
            </template>
          </el-table-column>
          <el-table-column label="输出格式" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ row.output_format?.toUpperCase() }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.created_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click.stop="editPreset(row)">
                编辑
              </el-button>
              <el-button size="small" @click.stop="duplicatePreset(row)">
                复制
              </el-button>
              <el-button size="small" type="danger" @click.stop="deletePreset(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && filteredPresets.length === 0" description="暂无预设" />

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="filteredPresets.length > 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 48, 96]"
            :total="filteredPresets.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
        />
      </div>

      <!-- 预设详情 -->
      <div v-if="selectedPreset && viewMode === 'grid'" class="preset-details">
        <h3>预设详情</h3>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="名称">{{ selectedPreset.name }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ selectedPreset.description || '无' }}</el-descriptions-item>
          <el-descriptions-item label="画布尺寸">
            {{ selectedPreset.canvas_width }} × {{ selectedPreset.canvas_height }}
          </el-descriptions-item>
          <el-descriptions-item label="输出格式">{{ selectedPreset.output_format?.toUpperCase() }}</el-descriptions-item>
          <el-descriptions-item label="人物缩放">{{ selectedPreset.video_scale }}</el-descriptions-item>
          <el-descriptions-item label="背景缩放">{{ selectedPreset.bg_scale }}</el-descriptions-item>
          <el-descriptions-item label="人物位置">
            X: {{ selectedPreset.video_x || 0 }}, Y: {{ selectedPreset.video_y || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="背景位置">
            X: {{ selectedPreset.bg_x || 0 }}, Y: {{ selectedPreset.bg_y || 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            :disabled="!selectedPreset"
            @click="applySelectedPreset"
        >
          应用选中预设
        </el-button>
      </div>
    </template>

    <!-- 创建/编辑预设对话框 -->
    <SavePresetDialog
        v-model="showCreateDialog"
        :preset="editingPreset"
        @save="handleSavePreset"
    />

    <!-- 导入预设对话框 -->
    <el-dialog v-model="showImportDialog" title="导入预设" width="500px">
      <el-upload
          class="import-upload"
          drag
          :auto-upload="false"
          :show-file-list="false"
          accept=".json"
          @change="handleImportFile"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将预设JSON文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持JSON格式的预设文件
          </div>
        </template>
      </el-upload>

      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SavePresetDialog from './SavePresetDialog.vue'
import api from '@/api'
import {Delete, DocumentCopy, Edit} from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'apply', 'save'])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value)
  }
})

// 响应式数据
const loading = ref(false)
const presets = ref([])
const searchKeyword = ref('')
const selectedPreset = ref(null)
const selectedPresets = ref([])
const showCreateDialog = ref(false)
const showImportDialog = ref(false)
const editingPreset = ref(null)
const viewMode = ref('grid')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12)

// 搜索防抖
let searchTimer = null

// 计算过滤后的预设
const filteredPresets = computed(() => {
  if (!searchKeyword.value) return presets.value

  const keyword = searchKeyword.value.toLowerCase()
  return presets.value.filter(preset =>
      preset.name.toLowerCase().includes(keyword) ||
      (preset.description && preset.description.toLowerCase().includes(keyword))
  )
})

// 当前页的预设
const currentPagePresets = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPresets.value.slice(start, end)
})

// 全选状态
const selectAll = computed({
  get: () => selectedPresets.value.length === currentPagePresets.value.length && currentPagePresets.value.length > 0,
  set: (value) => {
    if (value) {
      selectedPresets.value = [...currentPagePresets.value.map(p => p.id)]
    } else {
      selectedPresets.value = []
    }
  }
})

// 半选状态
const isIndeterminate = computed(() => {
  const selected = selectedPresets.value.length
  const total = currentPagePresets.value.length
  return selected > 0 && selected < total
})

// 方法
const loadPresets = async () => {
  loading.value = true
  try {
    const result = await api.getPresets()
    if (result.success) {
      presets.value = result.presets || []
    } else {
      ElMessage.error('加载预设失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载预设失败:', error)
    ElMessage.error('加载预设失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
  }, 300)
}

const handlePageSizeChange = () => {
  currentPage.value = 1
}

const handleCurrentPageChange = () => {
  selectedPresets.value = [] // 换页时清空选择
}

const selectPreset = (preset) => {
  selectedPreset.value = preset
}

const isPresetSelected = (presetId) => {
  return selectedPresets.value.includes(presetId)
}

const togglePresetSelection = (preset) => {
  const index = selectedPresets.value.indexOf(preset.id)
  if (index > -1) {
    selectedPresets.value.splice(index, 1)
  } else {
    selectedPresets.value.push(preset.id)
  }
}

const handleSelectAll = (value) => {
  if (value) {
    selectedPresets.value = currentPagePresets.value.map(p => p.id)
  } else {
    selectedPresets.value = []
  }
}

const handleTableSelection = (selection) => {
  selectedPresets.value = selection.map(item => item.id)
}

const clearSelection = () => {
  selectedPresets.value = []
}

const editPreset = (preset) => {
  editingPreset.value = preset
  showCreateDialog.value = true
}

const duplicatePreset = async (preset) => {
  try {
    const result = await api.duplicatePreset(preset.id)
    if (result.success) {
      ElMessage.success('预设复制成功')
      await loadPresets()
    } else {
      ElMessage.error('复制失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('复制预设失败:', error)
    ElMessage.error('复制失败')
  }
}

const deletePreset = async (preset) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除预设 "${preset.name}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const result = await api.deletePreset(preset.id)
    if (result.success) {
      ElMessage.success('预设删除成功')
      await loadPresets()

      // 如果删除的是当前选中的预设，清空选择
      if (selectedPreset.value?.id === preset.id) {
        selectedPreset.value = null
      }

      // 从选中列表中移除
      const index = selectedPresets.value.indexOf(preset.id)
      if (index > -1) {
        selectedPresets.value.splice(index, 1)
      }
    } else {
      ElMessage.error('删除失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除预设失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const batchDeletePresets = async () => {
  if (selectedPresets.value.length === 0) return

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedPresets.value.length} 个预设吗？`,
        '批量删除确认',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    let successCount = 0
    const errors = []

    for (const presetId of selectedPresets.value) {
      try {
        const result = await api.deletePreset(presetId)
        if (result.success) {
          successCount++
        } else {
          errors.push(`删除预设失败: ${result.message}`)
        }
      } catch (error) {
        errors.push(`删除预设失败: ${error.message}`)
      }
    }

    if (successCount > 0) {
      ElMessage.success(`成功删除 ${successCount} 个预设`)
      selectedPresets.value = []
      selectedPreset.value = null
      await loadPresets()
    }

    if (errors.length > 0) {
      ElMessage.warning(`${errors.length} 个预设删除失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const exportSelectedPresets = async () => {
  if (selectedPresets.value.length === 0) return

  try {
    const selectedPresetsData = presets.value.filter(p => selectedPresets.value.includes(p.id))
    const exportData = {
      presets: selectedPresetsData.map(preset => {
        const { id, created_time, updated_time, ...exportPreset } = preset
        return exportPreset
      }),
      exported_at: new Date().toISOString(),
      count: selectedPresetsData.length
    }

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `presets_selected_${new Date().getTime()}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    ElMessage.success(`成功导出 ${selectedPresetsData.length} 个预设`)
  } catch (error) {
    console.error('导出预设失败:', error)
    ElMessage.error('导出失败')
  }
}

const exportAllPresets = async () => {
  try {
    const result = await api.exportPresets()
    if (result.success) {
      const blob = new Blob([JSON.stringify(result, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `presets_all_${new Date().getTime()}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)

      ElMessage.success(`成功导出 ${result.count} 个预设`)
    }
  } catch (error) {
    console.error('导出预设失败:', error)
    ElMessage.error('导出失败')
  }
}

const handleImportFile = async (uploadFile) => {
  try {
    const file = uploadFile.raw
    const text = await file.text()
    const importData = JSON.parse(text)

    if (!importData.presets || !Array.isArray(importData.presets)) {
      ElMessage.error('无效的预设文件格式')
      return
    }

    const result = await api.importPresets(importData.presets)
    if (result.success) {
      ElMessage.success(result.message)
      showImportDialog.value = false
      await loadPresets()
    } else {
      ElMessage.error('导入失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('导入预设失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
  }
}

const applySelectedPreset = () => {
  if (selectedPreset.value) {
    emit('apply', selectedPreset.value)
    handleClose()
  }
}

const handleSavePreset = async (presetData) => {
  try {
    const result = await api.savePreset(presetData)
    if (result.success) {
      ElMessage.success('预设保存成功')
      await loadPresets()
      editingPreset.value = null
    } else {
      ElMessage.error('预设保存失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('保存预设失败:', error)
    ElMessage.error('保存预设失败')
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch {
    return '无效日期'
  }
}

const handleClose = () => {
  selectedPreset.value = null
  selectedPresets.value = []
  editingPreset.value = null
  visible.value = false
}

// 生命周期
onMounted(() => {
  if (visible.value) {
    loadPresets()
  }
})

// 监听弹窗显示
watch(visible, (newVal) => {
  if (newVal) {
    loadPresets()
  } else {
    selectedPresets.value = []
    selectedPreset.value = null
  }
})
</script>

<style lang="scss" scoped>
.preset-manager-dialog {
  ::v-deep(.el-dialog) {
    margin-top: 5vh;
    margin-bottom: 5vh;
    height: 90vh;

    .el-dialog__body {
      padding: 20px;
      height: calc(90vh - 120px);
      overflow: hidden;
    }
  }
}

.preset-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .header-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
  }

  .batch-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .normal-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.view-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.presets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.presets-table {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.preset-card {
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

    .preset-actions {
      opacity: 1;
    }
  }

  &.selected {
    border-color: #409eff;
    background: #f0f9ff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);

    // 选中时也显示操作按钮
    .preset-actions {
      opacity: 1;
    }
  }

  &.checked {
    background: #f5f7fa;
    border-color: #67c23a;

    // 勾选时也显示操作按钮
    .preset-actions {
      opacity: 1;
    }
  }

  .preset-checkbox {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 1;
  }

  .preset-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
    margin-top: 20px;

    .preset-name {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      flex: 1;
      margin-right: 10px;
    }

    .preset-actions {
      display: flex;
      gap: 4px;
      transition: opacity 0.3s ease;

      // 确保按钮可点击
      el-button {
        padding: 4px 8px;
      }
    }
  }

  .preset-description {
    color: #606266;
    font-size: 14px;
    margin-bottom: 12px;
    line-height: 1.4;
    min-height: 40px;
  }

  .preset-params {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 10px;
  }

  .preset-meta {
    color: #909399;
    font-size: 12px;
  }
}

.pagination-wrapper {
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
}

.preset-details {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
  margin-top: 20px;

  h3 {
    margin: 0 0 15px 0;
    color: #303133;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.import-upload {
  text-align: center;

  ::v-deep(.el-upload-dragger) {
    width: 100%;
    height: 180px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .manager-header {
    flex-direction: column;
    align-items: stretch;

    .header-actions {
      justify-content: center;
    }
  }

  .view-controls {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .presets-grid {
    grid-template-columns: 1fr;
  }
}
</style>